import { message } from 'antd';
import { routerRedux } from 'dva/router';
import * as servicesApi from '../services';

export default {
  spacename: 'goodsDetail',
  state: {
    categories: [], // 后台类目列表
    compenRule: [], // 赔偿规则列表
    rentRule: [], // 租赁规则列表
    backAddressList: [], // 归还地址列表
    goodsInfo: {
      mainImages: {
        fileList: [],
      },
      colorSpecs: [],
      otherSpecs: [],
      productSkuses: [
        {
          cycs: [
            {
              days: '1',
              price: '0.01',
            },
          ],
          specAll: [
            // {
            //   platformSpecId: '0',
            //   platformSpecName: '颜色',
            //   platformSpecValue: '默认',
            // },
            // {
            //   platformSpecId: '0',
            //   platformSpecName: '规格',
            //   platformSpecValue:'默认',
            // },
          ],
        },
      ],
    },
  },
  effects: {
    *selectShopRuleAndGiveBackByShopId(_, { call, put }) {
      const work = [
        call(servicesApi.findCategories),
        call(servicesApi.selectShopRuleAndGiveBackByShopId),
      ];

      const [cateRes, otherRes] = yield work;
      if (cateRes && otherRes) {
        yield put({
          type: 'setInitList',
          payload: { other: otherRes.data, cate: cateRes.data },
        });
      }
    },

    *selectProductEdit({ payload, callback }, { call, put }) {
      const res = yield call(servicesApi.selectProductEdit, payload);
      if (res) {
        callback(res.data.buyOutSupport);
        yield put({
          type: 'saveGoodsInfo',
          payload: res.data,
        });
      }
    },

    *updateBusProduct({ payload }, { call, put }) {
      const newInfo = { ...payload };
      console.log('newInfo:', newInfo);
      newInfo.categoryId = payload.categoryIds[payload.categoryIds.length - 1];
      newInfo.oldNewDegree = 1;
      newInfo.detail = payload.detail.toHTML().replace(/<img\/>/g, '');
      newInfo.images = payload.mainImages.fileList.map(file => file.response.data);
      newInfo.productSkuses = newInfo.productSkuses.map(sku => {
        const newSku = { ...sku };
        newSku.totalInventory = sku.inventory;
        return newSku;
      });
      if (newInfo.images.length == 0) {
        message.error('网速不给力，商品主图上传失败，请重新上传商品主图');
      }
      if (newInfo.productSkuses.length == 0) {
        message.error('网速不给力，SKU图片上传失败，请重新上传SKU图片');
      }
      if (newInfo.images.length > 0 && newInfo.productSkuses.length > 0) {
        const res = yield call(servicesApi.updateBusProduct, { ...newInfo });
        if (res) {
          message.success('商品修改成功');
          yield put(routerRedux.push('/goods/list'));
        }
      }
    },

    *changeSpecs({ payload, callback }, { put }) {
      if (payload.type === 'color') {
        yield put({
          type: 'setColorSpecs',
          payload: payload.specs,
        });
      }
      if (payload.type === 'other') {
        yield put({
          type: 'setOtherSpecs',
          payload: payload.specs,
        });
      }
      yield put({
        type: 'setProductSkus',
        payload: { ...payload, colorSpecId: '1', otherSpecId: '2', callback },
      });
    },

    *busInsertProduct({ payload }, { call, put }) {
      const newInfo = { ...payload };
      newInfo.categoryId = payload.categoryIds[payload.categoryIds.length - 1];
      newInfo.oldNewDegree = 1;
      newInfo.detail = payload.detail.toHTML().replace(/<img\/>/g, '');
      newInfo.images = payload.mainImages.fileList.map(file => file.response.data);
      newInfo.productSkuses = newInfo.productSkuses.map(sku => {
        const newSku = { ...sku };
        newSku.totalInventory = sku.inventory;
        return newSku;
      });
      if (newInfo.images.length == 0) {
        message.error('网速不给力，商品主图上传失败，请重新上传商品主图');
      }
      if (newInfo.productSkuses.length == 0) {
        message.error('网速不给力，SKU图片上传失败，请重新上传SKU图片');
      }
      if (newInfo.images.length > 0 && newInfo.productSkuses.length > 0) {
        const res = yield call(servicesApi.busInsertProduct, { ...newInfo });
        if (res) {
          message.success('商品保存成功');
          yield put(routerRedux.push('/goods/list'));
        }
      }
    },
  },
  reducers: {
    setInitList(state, { payload }) {
      return {
        ...state,
        compenRule: payload.other.compenRule,
        rentRule: payload.other.rentRule,
        backAddressList: payload.other.address,
        categories: payload.cate,
      };
    },
    saveGoodsInfo(state, { payload }) {
      const newInfo = { ...payload };
      newInfo.mainImages = {};
      const colorSpecs = [];
      const otherSpecs = [];
      payload.productSkuses.forEach(sku => {
        if (sku.specAll && sku.specAll.length) {
          // eslint-disable-next-line no-param-reassign
          sku.specAll = sku.specAll.sort(
            (a, b) => Number(a.platformSpecId) - Number(b.platformSpecId),
          );
          sku.specAll.forEach(spec => {
            if (spec.platformSpecName === '颜色') {
              colorSpecs.push(spec.platformSpecValue);
            }
            if (spec.platformSpecName === '规格') {
              otherSpecs.push(spec.platformSpecValue);
            }
          });
        }
      });
      newInfo.colorSpecs = [...new Set(colorSpecs)];
      newInfo.otherSpecs = [...new Set(otherSpecs)];
      newInfo.mainImages.fileList = payload.images.map((img, index) => {
        const obj = {
          uid: String(index),
          url: img,
          response: {
            data: img,
          },
        };
        return obj;
      });
      return { ...state, goodsInfo: newInfo };
    },
    setColorSpecs(state, { payload }) {
      return {
        ...state,
        goodsInfo: { ...state.goodsInfo, colorSpecs: payload },
      };
    },
    setOtherSpecs(state, { payload }) {
      return {
        ...state,
        goodsInfo: { ...state.goodsInfo, otherSpecs: payload },
      };
    },
    setProductSkus(state, { payload }) {
      const newColorSpecs =
        payload.type === 'color' ? [...payload.specs] : [...state.goodsInfo.colorSpecs];
      const newOtherSpecs =
        payload.type === 'other' ? [...payload.specs] : [...state.goodsInfo.otherSpecs];
      let newProductSkuses = [];
      const oldProductSkuses = [...state.goodsInfo.productSkuses];
      if (newColorSpecs.length) {
        newColorSpecs.forEach(color => {
          if (newOtherSpecs.length) {
            newOtherSpecs.forEach(other => {
              newProductSkuses.push({
                cycs: [
                  {
                    days: '1',
                    price: '0.01',
                  },
                ],
                specAll: [
                  {
                    platformSpecId: payload.colorSpecId,
                    platformSpecName: '颜色',
                    platformSpecValue: color,
                  },
                  {
                    platformSpecId: payload.otherSpecId,
                    platformSpecName: '规格',
                    platformSpecValue: other,
                  },
                ],
              });
            });
          } else {
            newProductSkuses.push({
              cycs: [
                {
                  days: '1',
                  price: '0.01',
                },
              ],
              specAll: [
                {
                  platformSpecId: payload.colorSpecId,
                  platformSpecName: '颜色',
                  platformSpecValue: color,
                },
              ],
            });
          }
        });
      } else if (newOtherSpecs.length) {
        newOtherSpecs.forEach(other => {
          newProductSkuses.push({
            cycs: [
              {
                days: '1',
                price: '0.01',
              },
            ],
            specAll: [
              {
                platformSpecId: payload.otherSpecId,
                platformSpecName: '规格',
                platformSpecValue: other,
              },
            ],
          });
        });
      } else {
        newProductSkuses.push({
          cycs: [
            {
              days: '1',
              price: '0.01',
            },
          ],
          specAll: [],
        });
      }

      if (oldProductSkuses.length) {
        newProductSkuses = newProductSkuses.map(newSku => {
          const index = oldProductSkuses.findIndex(oldSku => {
            if (newSku.specAll.length !== oldSku.specAll.length) {
              return false;
            }
            if (newSku.specAll.length === 0) {
              return true;
            }
            if (newSku.specAll.length === 1) {
              return newSku.specAll[0].platformSpecValue === oldSku.specAll[0].platformSpecValue;
            }
            if (newSku.specAll.length === 2) {
              return (
                newSku.specAll[0].platformSpecValue === oldSku.specAll[0].platformSpecValue &&
                newSku.specAll[1].platformSpecValue === oldSku.specAll[1].platformSpecValue
              );
            }
            return false;
          });
          if (index > -1) {
            return { ...oldProductSkuses[index] };
          }
          return newSku;
        });
      }
      payload.callback(newProductSkuses);
      return {
        ...state,
        goodsInfo: {
          ...state.goodsInfo,
          productSkuses: newProductSkuses,
        },
      };
    },
    setMainImage(state, { payload }) {
      return { ...state, goodsInfo: { ...state.goodsInfo, mainImages: { fileList: payload } } };
    },
    clearProduct(state) {
      return {
        ...state,
        goodsInfo: {
          mainImages: {
            fileList: [],
          },
          colorSpecs: [],
          otherSpecs: [],
          productSkuses: [
            // {
            //   cycs: [
            //     {
            //       days: '1',
            //       price: '0.01',
            //     },
            //   ],
            //   specAll: [
            //
            //   ],
            // },
          ],
        },
      };
    },
  },
};
